/**
 * utils file
 *
 */

export default class Utils {
  private constructor() {}

  /**
   * @description 生成全局唯一标识符
   * @return {String} uuid
   */
  public static uuid(): string {
    let uuid = '';
    for (let i = 0; i < 32; ++i) {
      const random = (Math.random() * 16) | 0;
      if (i === 8 || i === 12 || i === 16 || i === 20) uuid += '-';
      uuid += i === 12 ? 4 : (i === 16 ? (random & 3) | 8 : random).toString(16);
    }
    return uuid;
  }

  /**
   * @description 读写localStorage
   * @param  {string} namespace 键名
   * @param  {string[]} ...rest
   * @returns any
   */
  public static store(namespace: string, ...rest: any[]): any {
    if (rest.length) {
      return window.localStorage.setItem(namespace, JSON.stringify(rest[0]));
    } else {
      const data = window.localStorage.getItem(namespace);
      return data && JSON.parse(data);
    }
  }

  /**
   * @description 读写cookie
   * @param  {string} namespace 键名
   * @param  {string} value 键值
   * @param  {number} date 有效时间(天数)
   * @returns string | undefined
   */
  public static cookie(namespace: string, value: string = '', date: number = 10): string | undefined {
    if (!value || !value.trim()) {
      // 读取cookie
      const cookieStr = window.document.cookie;
      if (!cookieStr || !cookieStr.trim()) return;
      const cookies = cookieStr.split('; ');
      for (const cookie of cookies) {
        const cookieArr = cookie.split('=');
        if (cookieArr[0].trim() === namespace.trim()) {
          return unescape(cookieArr[1]);
        }
      }
      return;
    } else {
      // 写入cookie
      const now = new Date();
      now.setTime(now.getTime() + date * 24 * 60 * 60 * 1000);
      const expireTime = now.toUTCString();
      window.document.cookie = `${namespace}=${value}; expires=${expireTime}; path=/`;
      return;
    }
  }

  /**
   * @description 读写SessionStorage
   * @param  {string} namespace 键名
   * @param  {any} value 键值
   * @return {any}
   */
  public static session(namespace: string, value: any = null): any {
    if (value !== null && value !== undefined) {
      window.sessionStorage.setItem(namespace, JSON.stringify(value));
    } else {
      const data = window.sessionStorage.getItem(namespace);
      return data && JSON.parse(data);
    }
  }
}
